using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SubstrateHelper.Data;


namespace SubstrateHelper
{
    public class Program
    {
        public static IServiceProvider ServiceProvider;
        public static void Main(string[] args)
        {


            //var host = CreateHostBuilder(args).Build();
            var host = CreateWebHostBuilder(args).Build();
            ServiceProvider = host.Services;
            Global.Host = host;
            CreateDbIfNotExists(host);

            Init.DoSomeInit(host);
            //DoSomeInit(host);
            
            host.Run();

            //CreateWebHostBuilder(args).Build().Run();

        }

        private static void CreateDbIfNotExists(IWebHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                

                try
                {
                    var context = services.GetRequiredService<SubstrateHelperDbContext>();
                    context.Database.EnsureCreated();       
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred creating the DB.");
                }
            }
        }
        

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
            //.UseUrls("http://*:5000;https://*:5001");
            .UseUrls("http://*:5000");

    }
}
